package com.jyszkj.map.util

import android.content.Context
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream

object FileUtils {


    /**
     * 将 assets 文件复制到缓存目录
     */
    fun copyAssetToCache(context: Context, assetPath: String, catchFile: String): File? {
        return try {
            // 创建缓存目录
            val cacheDir = File(catchFile)
            if (!cacheDir.exists()) {
                cacheDir.mkdirs()
            }

            // 创建目标文件
            val outputFile = File(cacheDir, File(assetPath).name)

            // 复制文件
            context.assets.open(assetPath).use { input ->
                FileOutputStream(outputFile).use { output ->
                    input.copyTo(output)
                }
            }

            outputFile
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 解压 ZIP 文件
     */
    private fun unzipFile(zipFile: File, targetDir: File): Boolean {
        return try {
            if (!targetDir.exists()) {
                targetDir.mkdirs()
            }

            ZipInputStream(FileInputStream(zipFile)).use { zipInputStream ->
                var zipEntry: ZipEntry?
                val buffer = ByteArray(1024)

                while (zipInputStream.nextEntry.also { zipEntry = it } != null) {
                    val entry = zipEntry!!
                    val entryFile = File(targetDir, entry.name)

                    if (entry.isDirectory) {
                        entryFile.mkdirs()
                    } else {
                        // 确保父目录存在
                        entryFile.parentFile?.mkdirs()

                        FileOutputStream(entryFile).use { output ->
                            var len: Int
                            while (zipInputStream.read(buffer).also { len = it } > 0) {
                                output.write(buffer, 0, len)
                            }
                        }
                    }
                }
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
}